package com.wy.tranFile.service.impl;

import com.wy.tranFile.bean.Constant;
import com.wy.tranFile.pojo.FileInfo;
import com.wy.tranFile.bean.FileMap;
import com.wy.tranFile.pojo.Result;
import com.wy.tranFile.service.TranFileService;
import com.wy.tranFile.util.FileNameUtils;
import com.wy.tranFile.util.TimeUtil;
import com.wy.tranFile.util.UUIDUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@Service
public class TranFileServiceImpl implements TranFileService {

    @Autowired
    private Constant constant;
    @Autowired
    private FileMap fileMap;

    @Override
    public Result uploadFile(MultipartFile multipartFile) throws Exception {
        try {
            String uuid = UUIDUtils.getUUID();
            File dirPath = new File(constant.getAddress() + TimeUtil.getCurrentTimePath() + uuid);
            if (!dirPath.exists()) {
                if (!dirPath.mkdirs()) {
                    System.out.println("上传失败-》文件创建失败：" + dirPath);
                }
            }
            String quanPath = dirPath.getPath() + "//" + FileNameUtils.doOkFileName(uuid, multipartFile.getOriginalFilename());
            FileOutputStream fileOutputStream = new FileOutputStream(new File(quanPath), true);
            fileOutputStream.write(multipartFile.getBytes());
            fileOutputStream.close();
            FileInfo fileInfo = new FileInfo();
            fileInfo.setPathDir(quanPath);
            fileInfo.setFileName(multipartFile.getOriginalFilename());
            fileMap.put(uuid, fileInfo);
            System.out.println("上传成功："+uuid);
            return Result.success(uuid);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Result.fail();
    }

    @Override
    public byte[] down(String id) throws IOException {
        if (id != null && id.length() != 0) {
            boolean exists = fileMap.exists(id);
            if (exists) {
                FileInfo fileInfo = fileMap.get(id);
                String path = fileInfo.getPathDir();
                //这是一个文件，
                File file = new File(path);
                if (!file.exists()) {
//                    如果文件不存在 那是一个异常，文件丢失
                    throw new RuntimeException("存储文件丢似乎异常。id = " + id);
                } else {
                    byte[] bytes = new byte[(int) file.length()];
                    FileInputStream fileInputStream = new FileInputStream(file);
                    fileInputStream.read(bytes);
                    fileInputStream.close();
                    return bytes;
                }
            } else {
//                id有误
                return null;
            }
        } else {
            return null;
        }
    }
}
